package services

import (
	"bsm/constants"
	"bsm/daos"
	"bsm/logger"
	"bsm/models"
	"bsm/utils"
	"crypto/md5"
	"fmt"
)

type UserService interface {
	GetUserProfile(userID string) (*models.ProjectUser, error)
	ChangePassword(userID string, oldPassword, newPassword string) error
	AddUser(user models.ProjectUser, userRole []string) error
	UpdateUser(user models.ProjectUser, userRole []string) error
	GetRoles() ([]models.Role, error)
	GenerateUserId(username string) (string, error)
	DeleteUser(userID string) error
	//CheckUserRole(userID string, roleID string) (bool, error)
	ResetPassword(userID string) error
	FreezeUser(userID string) error
	UnfreezeUser(userID string) error
	CheckUserRole(userID string, roleID string) (bool, error)
}
type userServiceImpl struct {
	userDao daos.UserDao
}

func NewUserService(userDao daos.UserDao) UserService {
	return &userServiceImpl{
		userDao: userDao,
	}
}

// GetUserProfile 获取用户详细信息
func (s *userServiceImpl) GetUserProfile(userID string) (*models.ProjectUser, error) {
	return s.userDao.GetUserByUserID(userID)
}

// UpdateUserProfile 更新用户信息
// func (s *UserService) UpdateUserProfile(userID int, updateData map[string]interface{}) error {
// 	return s.userDAO.UpdateUser(userID, updateData)
// }

// ChangePassword 修改密码
func (s *userServiceImpl) ChangePassword(userID string, oldPassword, newPassword string) error {
	// 这里可以添加密码验证和加密逻辑
	hash_old := md5.Sum([]byte(userID + "-" + oldPassword))
	hashStr_old := fmt.Sprintf("%x", hash_old)
	hash_new := md5.Sum([]byte(userID + "-" + newPassword))
	hashStr_new := fmt.Sprintf("%x", hash_new)

	ok, _ := s.userDao.CheckUserPassword(userID, hashStr_old)
	if !ok {
		return fmt.Errorf("原密码错误！")
	}

	err := s.userDao.UpdatePassword(userID, hashStr_new)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "service",
			"operation": "userService-ChangePassword",
		}).Errorf("ChangePassword failed - userID: %s, error: %s", userID, err)
		return err
	}
	return nil
}

func (s *userServiceImpl) AddUser(user models.ProjectUser, userRole []string) error {
	// 检查用户名是否已存在
	if user.Password != "" {
		hash_new := md5.Sum([]byte(user.UserID + "-" + user.Password))
		hashStr_new := fmt.Sprintf("%x", hash_new)
		user.Password = hashStr_new
	}

	err := s.userDao.InTransaction(func() error {
		err := s.userDao.AddUser(&user)
		if err != nil {
			logger.WithFields(map[string]interface{}{
				"layer":     "service",
				"operation": "userService-AddUser",
			}).Errorf("AddUser failed - username: %s, error: %s", user.UserName, err)
			return err
		}

		// 检查角色是否存在
		for _, role := range userRole {
			user_role := models.UserRole{
				UserID: user.UserID,
				RoleID: role,
			}
			err = s.userDao.AddUserRole(&user_role)
			if err != nil {
				logger.WithFields(map[string]interface{}{
					"layer":     "service",
					"operation": "AddUser",
				}).Errorf("AddUser failed - role: %s, error: %s", role, err)
				return err
			}
		}

		return nil
	})
	if err != nil {
		return err
	}
	return nil
}

// UpdateUser 更新用户信息
func (s *userServiceImpl) UpdateUser(user models.ProjectUser, userRole []string) error {
	// 检查用户名是否已存在
	err := s.userDao.InTransaction(func() error {
		err := s.userDao.UpdateUser(&user)
		if err != nil {
			logger.WithFields(map[string]interface{}{
				"layer":     "service",
				"operation": "userService-UpdateUser",
			}).Errorf("UpdateUser failed - username: %s, error: %s", user.UserName, err)
			return err
		}
		// 删除用户角色
		err = s.userDao.DeleteUserRoles(user.UserID)
		if err != nil {
			logger.WithFields(map[string]interface{}{
				"layer":     "service",
				"operation": "UpdateUser",
			}).Errorf("UpdateUser failed - userID: %s, error: %s", user.UserID, err)
			return err
		}
		// 添加用户角色
		for _, role := range userRole {
			user_role := models.UserRole{
				UserID: user.UserID,
				RoleID: role,
			}
			err = s.userDao.AddUserRole(&user_role)
			if err != nil {
				logger.WithFields(map[string]interface{}{
					"layer":     "service",
					"operation": "UpdateUser",
				}).Errorf("UpdateUser failed - role: %s, error: %s", role, err)
				return err
			}
		}
		return nil
	})
	if err != nil {
		return err
	}
	return nil
}

// GetRoles 获取角色列表
func (s *userServiceImpl) GetRoles() ([]models.Role, error) {
	roles, err := s.userDao.GetRoles()
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "service",
			"operation": "GetRoles",
		}).Errorf("GetRoles: failed to get roles: %v", err)
		return nil, err
	}
	return roles, nil
}

// GenerateUserId 生成用户ID
func (s *userServiceImpl) GenerateUserId(username string) (string, error) {
	userID := utils.GetPinyin(username)
	return userID, nil
}

// DeleteUser 删除用户
func (s *userServiceImpl) DeleteUser(userID string) error {
	return s.userDao.DeleteUser(userID)
}

func (s *userServiceImpl) ResetPassword(userID string) error {
	// 生成新密码
	newPassword := constants.DefaultPassword
	hash_new := md5.Sum([]byte(userID + "-" + newPassword))
	hashStr_new := fmt.Sprintf("%x", hash_new)

	// 更新用户密码
	return s.userDao.UpdatePassword(userID, hashStr_new)
}

func (s *userServiceImpl) FreezeUser(userID string) error {
	return s.userDao.FreezeUser(userID)
}

// UnfreezeUser 解冻用户
func (s *userServiceImpl) UnfreezeUser(userID string) error {
	return s.userDao.UnfreezeUser(userID)
}

func (s *userServiceImpl) CheckUserRole(userID string, roleID string) (bool, error) {
	hasRole, err := s.userDao.CheckUserRole(userID, roleID)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "service",
			"operation": "CheckUserRole",
		}).Errorf("CheckUserRole failed - userID: %s, error: %s", userID, err)
		return false, err
	}
	return hasRole, nil
}
